import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute, Params } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { IEntityDtoOfGuid,PageMessageInput,MessagesStateInput,MessageSelectInput,MessageSelectItem,
  MesssageExportList,MessagesServiceProxy} from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/service/file-download.service';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { map as _map } from 'lodash-es';
import { EditMessageModalComponent } from './edit-message.component';
import { ContentPermissionService } from '../shared/permissions/content-permission.service';
import { FileUpload } from 'primeng/fileupload';
import { AppConsts } from '@shared/AppConsts';

@Component({
  templateUrl: './message.component.html',
  animations: [appModuleAnimation()]
})
export class MessageComponent extends AppComponentBase {

  @ViewChild('dataTable', { static: true }) dataTable: Table;
  @ViewChild('paginator', { static: true }) paginator: Paginator;
  @ViewChild('editMessageModal', { static: true }) editMessageModal: EditMessageModalComponent;

  advancedFiltersAreShown = false;
  filterText = '';
  titleFilter='';
  menuFilter='';
  sourceMenuId = 0;
  relevanceId = '';
  timePhasing = 0;
  MessageReleaseState=0;
  kind: number;
  selectedDatas: IEntityDtoOfGuid[];
  recArr: MessageSelectItem[] = [];
  permissionDic: { [key: string]: boolean } = {};

  constructor(
    injector: Injector,
    private _activatedRoute: ActivatedRoute,
    private _messagesServiceProxy: MessagesServiceProxy,
    private _contentPermissionService: ContentPermissionService,
    private _fileDownloadService:FileDownloadService
  ) {
    super(injector);
  }

  ngOnInit() {
    this._activatedRoute.params.subscribe((params: Params) => {
      this.kind = Number(params['kind']);
      this.resetParamDatas();
      this._contentPermissionService.getContentPermissionData(AppConsts.PermssionModules.message, this.kind, (result) => {
        this.permissionDic = result;
      });
      this._messagesServiceProxy.getMessageSelectMenuData(new MessageSelectInput({
        menuId:this.kind,
        titleFilter:"",
        menuFilter:""
      })).subscribe(result => {
        this.recArr = result;
    });
      this.dataTable.reset();

      if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
        this.getLists(null);
      }
    });
  }
  getLists(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
        return;
      }
    }
    this.selectedDatas = [];
    this.primengTableHelper.showLoadingIndicator();
    this._messagesServiceProxy.getPagedMessagesData(new PageMessageInput({
      menuId: this.kind,
      timePhasing: this.timePhasing,
      enabled:this.MessageReleaseState,
      filter: this.filterText,
      titleFilter:this.titleFilter,
      menuFilter:this.menuFilter,
      startTime:null,
      endTime:null,
      sorting: this.primengTableHelper.getSorting(this.dataTable),
      maxResultCount: this.primengTableHelper.getMaxResultCount(this.paginator, event),
      skipCount: this.primengTableHelper.getSkipCount(this.paginator, event),
  })).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
      this.primengTableHelper.totalRecordsCount = result.totalCount;
      this.primengTableHelper.records = result.items;
      this.primengTableHelper.hideLoadingIndicator();
    });
  }

  delete(): void {
    this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
      (isConfirmed) => {
        if (!isConfirmed) return;
        this._messagesServiceProxy.deleteMessages(this.getSelectedIds(), this.kind)
          .subscribe(() => {
            this.reloadPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      })
  }

  getSelectedIds() {
    return _map(this.selectedDatas, selectedMember => selectedMember.id);
  }

  reloadPage() {
    if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
      return;
    }

    this.getLists(null);
  }

  editJob(record) {
    this.editMessageModal.show(record.id, this.kind, this.permissionDic);
  }

  changeState(enabled)
  {
    var text=enabled==true?this.l('ReleaseWarningAudit'):this.l('UndoWarningAudit');
    this.message.confirm(text, this.l('AreYouSure'),
      (isConfirmed) => {
        if (!isConfirmed) return;
        this._messagesServiceProxy.updateMessagesState(new MessagesStateInput({
        ids:this.getSelectedIds(),
        enabled:enabled,
        menuId: this.kind
        })).subscribe(() => {
            this.reloadPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      })
  }

  // TODO : 待完善
  exportToExcel(): void {
    this.message.confirm(this.l('ExportToExcel'), this.l('AreYouSure'),
      (isConfirmed) => {
        if (!isConfirmed) return;
        let ids = this.selectedDatas.map(item => item.id);
        this._messagesServiceProxy.dataExport(new MesssageExportList({
          list: ids,
          startTime: null,
          endTime: null,
          enabled: this.MessageReleaseState,
          menuId: this.kind,
          filter: this.filterText,
          titleFilter:this.titleFilter,
      menuFilter:this.menuFilter,
          sorting: '',
          company: '',
        })).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
          this.selectedDatas = [];
          this._fileDownloadService.downloadTempFile(result);
      })
    })
  }

onUploadExcelError(): void {
    this.notify.error(this.l('ImportUsersUploadFailed'));
}

  private resetParamDatas() {
    this.filterText = "";
    this.titleFilter="";
    this.menuFilter="";
    this.sourceMenuId = 0;
    this.relevanceId = '';
    this.timePhasing = 0;
    this.MessageReleaseState=0;
    this.permissionDic = {};
    this.advancedFiltersAreShown = false;
  }

}
